package com.peng.mvvm_wan.viewmodels

import androidx.lifecycle.MutableLiveData
import com.peng.mvvm_wan.beans.BaseResp
import com.peng.mvvm_wan.beans.LoginBean
import com.peng.safety.utils.CODE_SUCC
import com.peng.safety.utils.Logd
import com.peng.safety.utils.SnackUtil

class LoginModel : BaseModel() {

    var loginInfo: MutableLiveData<LoginBean> = MutableLiveData()

    var inputUserName = MutableLiveData<String>()
    var inputPassword = MutableLiveData<String>()
    var canLogin = MutableLiveData<Boolean>()

    init {
        inputUserName.observeForever {
            canLogin.value =
                inputUserName.value!!.isNotEmpty() && inputPassword.value!!.isNotEmpty()
        }
        inputPassword.observeForever {
            canLogin.value =
                inputUserName.value!!.isNotEmpty() && inputPassword.value!!.isNotEmpty()
        }
        inputUserName.value = ""
        inputPassword.value = ""
    }

    fun doLogin() {
        Logd("doLogin: name=${inputUserName.value},,,,psw=${inputPassword.value}")
        apiDSL<BaseResp<LoginBean>> {
            onRequest {
                service.requestLogin(inputUserName.value ?: "", inputPassword.value ?: "")
            }
            onResponse {
                if (it.errorCode == CODE_SUCC) {
                    loginInfo.value = it.data
                } else {
                    SnackUtil.show(it.errorMsg, false)
                }

            }
            onError {
                SnackUtil.show(it.message, false)
                true
            }
        }
    }


}